package com.hiray.demos

import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

/**
 * Created by hiray on 2018/5/24.
 *@author hiray
 */
class ItemAdapter(private var items: List<String>, private var onItemClickListener: OnItemClickListener?) : androidx.recyclerview.widget.RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {

    private var layoutInflater: LayoutInflater? = null
    private val layoutId = R.layout.demo_item
    var cornerMarker: Boolean = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        if (layoutInflater == null)
            layoutInflater = LayoutInflater.from(parent.context)
        return ItemViewHolder(layoutInflater!!.inflate(layoutId, parent, false))
    }

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        if (cornerMarker) {
            holder.cornerMarker.visibility = View.VISIBLE
            holder.cornerMarker.text = holder.adapterPosition.toString()
        } else holder.cornerMarker.visibility = View.GONE
        holder.textView.text = items[holder.adapterPosition]
        if (onItemClickListener != null)
            holder.itemView.setOnClickListener({
                onItemClickListener!!.onItemClick(holder.adapterPosition)
            })
    }


    class ItemViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
        var textView: AppCompatTextView = itemView?.findViewById(R.id.item_name) as AppCompatTextView
        var cornerMarker: AppCompatTextView = itemView?.findViewById(R.id.corner_marker) as AppCompatTextView
    }


    interface OnItemClickListener {
        fun onItemClick(position: Int): Unit
    }
}